<template>
  <div>
    <SupInput
      :InpList="InpList"
      :BtnList="BtnList"
      @clickFn="addFindFn"
    ></SupInput>
    <Suptable
      :headerData="headerData"
      :tableData="tableData"
      :isImg="true"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      :current-page="pagenum"
      :total="total"
      :pagesizeList="fenye"
      :pagesize="pagesize"
    >
      <template v-slot:imgSlot="{ row }">
        <div>
          <img :src="row.row.url" alt="" width="100" height="50" />
        </div>
      </template>
      <template v-slot:opera="{ row }">
        <div>
          <el-button
            type="text"
            @click="goEdit('2', row.row.id, row.row)"
            size="small"
            >编辑</el-button
          >
          <el-button type="text" @click="godelete(row.row.id)" size="small"
            >删除</el-button
          >
        </div>
      </template>
    </Suptable>
    <div>
      <el-dialog
        :title="dialogtype == '1' ? '新增' : '编辑'"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <span slot="footer" class="dialog-footer">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="广告名" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="广告内容" prop="content"  id="kuan">
              <el-input v-model="ruleForm.content"></el-input>
            </el-form-item>
            <el-form-item label="广告位置" prop="position">
              <el-input v-model="ruleForm.position"></el-input>
            </el-form-item>
            <el-form-item label="是否启用" prop="enabled">
              <el-input v-model="ruleForm.enabled"></el-input>
            </el-form-item>
            <el-form-item label="链接" v-if="dialogtype == 1">
              <el-input v-model="ruleForm.link"></el-input>
            </el-form-item>
            <el-form-item label="图片" v-if="dialogtype == 1">
              <el-upload
                class="avatar-uploader"
                action="https://www.shequlianshang.com/test/admin/storage/create"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >确认</el-button
              >
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Suptable from "@/components/Suptable";
import SupInput from "@/components/SupInput";
import { advertList, detAdvert, addAdvert, editAdvert,queryAdvert } from "@/api/spreadMock";
export default {
  name: "advertising",
  data() {
    return {
      pagenum: 1,
      total: 0,
      pagesize: 5,
      fenye: [5, 10, 15, 20],
      dialogVisible: false,
      dialogtype: 1,
      tableData: [],
      headerData: [
        {
          prop: "id",
          label: "广告ID",
          width: "200",
        },
        {
          prop: "name",
          label: "广告标题",
          width: "200",
        },
        {
          prop: "content",
          label: "广告内容",
          width: "200",
        },
        {
          prop: "position",
          label: "广告位置",
          width: "200",
        },
        {
          prop: "link",
          label: "活动链接",
          width: "200",
        },
        {
          prop: "enabled",
          label: "是否启用",
          width: "200",
        },
      ],
      InpList: [
        {
          model: "",
          text: "请输入商品名称",
        },
      ],
      BtnList: [
        {
          icon: "el-icon-search",
          name: "查找",
        },
        {
          icon: "el-icon-edit",
          name: "添加",
        },
      ],
      imageUrl: "",
      ruleForm: {
        id:'',
        name: "",
        content: "",
        position: "",
        enabled: "",
        link: "",
        url: "",
      },
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        content: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        position: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        enabled: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    let _self = this;
    _self.userList();
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    userList() {
      let _self = this;
      let data = {
        pagesize: _self.pagesize,
        pagenum: _self.pagenum,
      };
      advertList(data).then((res) => {
        // console.log(res);
        if (res.meta.status == 200) {
          _self.tableData = [];
          for (let item of res.data.user) {
            let userData = {
              content: item.content,
              enabled: item.enabled == true ? "启用" : "不启用",
              id: item.id,
              link: item.id,
              name: item.name, // 广告位置 1首页  2个人中心  3 购物车
              position:
                item.position == 1
                  ? "首页"
                  : item.position == 2
                  ? "个人中心"
                  : "购物车",
              url: item.url,
            };
            _self.tableData.push(userData);
          }
          _self.total = res.data.total;
          _self.pagenum = res.data.pagenum;
        }
      });
    },
   
    godelete(id) {
      let _self = this;
      _self
        .$confirm("确定删除吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let data = { id };
          detAdvert(data).then((res) => {
            // console.log(res);
            if (res.meta.status == 200) {
              _self.$message({
                type: "success",
                message: "删除成功",
              });
              _self.userList();
            } else {
              _self.$message({
                type: "info",
                message: res.meta.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(val) {
      let _self = this;
        _self.pagesize = val
      _self.userList();
    },
    handleCurrentChange(val) {
      let _self = this;
      _self.pagenum = val;
    
      _self.userList();
    },
    addFindFn(index) {
      let _self = this;
      _self.dialogtype = 1;
      if (index == 1) {
        _self.dialogVisible = true;
        _self.ruleForm = {
        name: "",
        content: "",
        position: "",
        enabled: "",
        link: "",
        url: "",   
        };
      }else if (index==0){
        let data = {
          name: _self.InpList[0].model,
        };
        queryAdvert(data).then((res)=>{
          // console.log(res);
           _self.tableData = [];
          if(res.meta.status==200){
              for (let item of res.data.arr) {
                let userData = {
                  id:item.id,
                  name:item.name,
                  content:item.content,
                  position:item.position,
                  enabled:item.enabled,
                  link:item.link,
                  url:item.url,
                }
                 _self.tableData.push(userData);
              }
          }else{
            _self.userList()
          }
        })
      }
    },
    submitForm(formName) {
      let _self = this;
      _self.dialogVisible = false;
      if (_self.dialogtype == 1) {
        _self.$refs[formName].validate((valid) => {
          if (valid) {
            let { name, content, position, enabled, link } = _self.ruleForm;
            let data = {
              name,
              content,
              position,
              enabled,
              link,
              url: _self.imageUrl,
            };
            addAdvert(data).then((res) => {
              let _self = this;
              if (res.meta.status == 200) {
                _self.$refs[formName].resetFields();
                _self.imageUrl = "";
                _self.userList();
              } else {
                _self.$message({
                  type: "info",
                  message: "res.meta.msg",
                });
              }
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
            let { id } = _self.ruleForm;
            let data = {
              id,
              content: _self.ruleForm.content,
              name: _self.ruleForm.name,
              position: _self.ruleForm.position,
              enabled: _self.ruleForm.enabled,
            };
            editAdvert(data).then((res) => {
              // console.log(res);
              if (res.meta.status == 200) {
                _self.userList();
                 _self.$refs[formName].resetFields();
              }
            });
          } 
     
     
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
     goEdit(type, id, row) {
      let _self = this;
      _self.dialogtype = 2;
      _self.dialogVisible = true;
      _self.ruleForm = {
        id,
        content: row.content,
        name: row.name,
        position: row.position,
        enabled: row.enabled,
      };
    },
  },

  components: { Suptable, SupInput },
};
</script>
<style>
.avatar-uploader {
  text-align: left;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>